const app = getApp();
Page({
  data: {
    server:app.globalData.server,
    api:app.globalData.api,
    token:'',
    orderInfo:[],
    defaultAddress:null,
    defaultAddressId:null,
    totalNum:0,
    totalPrice:0,
    modalOpened: false,
    buttons: [
      { text: '取消' },
      { text: '支付' },
    ],
    sharePid:null,
    userId:null
  },
  onShow() {
    let that = this;
    my.getStorage({
      key: 'userInfo',
      success: function(res) {
        console.log(res.data);
        that.setData({
          token:res.data?res.data.token:'',
          userId:res.data?res.data.userInfo.id:null,
        })
        that.getOrderInfo()
      }
    });
  },
  onHide() {
    my.removeStorage({
      key: 'selectedAddress'
    });
    my.removeStorage({
      key: 'shareInfo'
    });
  },
  getDefaultAddress(){
    let that = this;
    my.request({
      url:this.data.api+"/user/defaultAddress",
      method: 'get',
      headers:{
        'content-type':'application/json',
        'token':this.data.token
      },
      dataType: 'json',
      success: function(res) {
        console.log(res)
        if(res.data.errCode==401){//token过期了
          my.removeStorage({
            key: 'userInfo'
          });
          that.setData({
            token:'',
            userId:null
          })
          my.showToast({
            type: 'exception',
            content: res.data.message,
            duration: 2000
          });
          my.reLaunch({ url: '../login/login' });
          return false
        }else if(res.data.errCode==9){
          console.log('没有默认地址')
          that.getAddressList()
        }else if(res.data.errCode==0){
          that.setData({
            defaultAddress:res.data.result
          })
        }
      }
    });
  },
  getAddressList(){
    let that = this;
    my.request({
      url:this.data.api+'/user/addressList?page=1',
      method: 'get',
      headers:{
        'content-type':'application/json',
        'token':this.data.token
      },
      dataType: 'json',
      success: function(res) {
        console.log(res)
        if(res.data.errCode==401){//token过期了
          my.removeStorage({
            key: 'userInfo'
          });
          that.setData({
            token:'',
            userId:null,
            orderInfo:[],
            defaultAddress:null,
            defaultAddressId:null,
            totalNum:0,
            totalPrice:0,
          })
          my.showToast({
            type: 'exception',
            content: res.data.message,
            duration: 2000
          });
          my.reLaunch({ url: '../login/login' });
          return false
        }else if(res.data.errCode==0){
          if(res.data.data.result.length>0){
            that.setData({
              defaultAddress:res.data.data.result[0]
            })
          }
        }
      }
    });
  },
  getAddressItem(id){
    let that = this;
    my.request({
      url:this.data.api+"/user/addressItem?id="+id,
      method: 'get',
      headers:{
        'content-type':'application/json',
        'token':this.data.token
      },
      dataType: 'json',
      success: function(res) {
        console.log(res)
        if(res.data.errCode==401){//token过期了
          my.removeStorage({
            key: 'userInfo'
          });
          that.setData({
            token:'',
            userId:null
          })
          my.showToast({
            type: 'exception',
            content: res.data.message,
            duration: 2000
          });
          my.reLaunch({ url: '../login/login' });
          return false
        }
        if(res.data.errCode==0){
          that.setData({
            defaultAddress:res.data.result
          })
        }
      }
    });
  },
  //从缓存读取订单数据
  getOrderInfo(){
    let that = this;
    my.getStorage({
      key: 'selectedAddress',
      success: function(res) {
        if(res.data){
          that.setData({
            defaultAddressId:res.data
          })
          //通过id获取地址
          that.getAddressItem(that.data.defaultAddressId)
        }else{
          //用默认地址
          that.getDefaultAddress()
        }
      },
      fail: function(res){
        console.log(res.errorMessage)
      }
    });
    my.getStorage({
      key: 'orderInfo',
      success: function(res) {
        // let count=0,totalPrice=0;//总数，总价
        // let list = res.data;
        // list.forEach((value,index,array)=>{
        //   count+=value.num;
        //   totalPrice+=value.num*value.price;
        // })
        if(res.data){
          let totalPrice = res.data.num*res.data.price;
          that.setData({
            orderInfo:res.data,
            totalNum:res.data.num,
            totalPrice:totalPrice
          })
        }else{
          that.setData({
            orderInfo:null,
          })
          if(!that.data.orderInfo){
            my.switchTab({ url: '../index/index' })
          }
        }
        // console.log(that.data.orderInfo)
        // console.log(that.data.totalNum);
        // console.log(that.data.totalPrice);
      },
      fail: function(res){
        console.log(res.errorMessage)
      }
    });
  },
  bindSelectAddress(){
    my.navigateTo({ url: '../address/address?confirmToAddress=1' })//confirmToAddress=1标志从确定订单页面跳转到地址页
  },
  openModal() {
    console.log(this.data.defaultAddress)
    if(!this.data.defaultAddress){
      my.showToast({
        type: 'fail',
        content: '请选择收货地址',
        duration: 2000
      });
      return 
    }
    this.setData({
      modalOpened: true,
    });
  },
  onButtonClick(e) {
    console.log(e.target.dataset.index)//0取消，1支付
    let toPay = e.target.dataset.index;
    //调支付接口
    let that = this;
    my.getStorage({
      key: 'shareInfo',
      success: function(res) {
        console.log(res.data)
        if(res.data){//订单id和缓存的订单id
          if(res.data.productId==that.data.orderInfo.id && res.data.pid!=that.data.userId){//自己分享给自己是没有佣金的
            that.setData({
              sharePid:res.data.pid
            })
          }
        }
        that.submitOrder(toPay)
      }
    });
  },
  submitOrder(toPay){
    //提交订单
    let payInfo = {
      product_id:this.data.orderInfo.id,
      price:this.data.orderInfo.price,
      num:this.data.totalNum,
      total_price:this.data.totalPrice,
      address:this.data.defaultAddress.address,
      order_payment_status:toPay,//0为取消支付，1为支付成功
      pid:this.data.sharePid?this.data.sharePid:1//没有人分享来的pid为0
    }
    console.log(payInfo)

    let that = this;
    my.request({
      url:this.data.api+"/user/pay",
      method: 'post',
      headers:{
        'content-type':'application/json',
        'token':this.data.token
      },
      dataType: 'json',
      data:payInfo,
      success: function(res) {
        console.log(res)
        my.removeStorage({
          key: 'orderInfo'
        });
        my.removeStorage({
          key: 'selectedAddress'
        });
        my.removeStorage({
          key: 'shareInfo'
        });
        that.setData({
          modalOpened: false
        })
        if(res.data.errCode==401){//token过期了
          my.removeStorage({
            key: 'userInfo'
          });
          that.setData({
            token:'',
            userId:null,
            orderInfo:[],
            defaultAddress:null,
            defaultAddressId:null,
            totalNum:0,
            totalPrice:0,
          })
          my.showToast({
            type: 'exception',
            content: res.data.message,
            duration: 2000
          });
          my.reLaunch({ url: '../login/login' });
          return false
        }else if(res.data.errCode==9){
          my.showToast({
            type: 'fail',
            content: res.data.message,
            duration: 2000,
            success:function(){
              my.redirectTo({ url: '../order/order' });
            }
          });
        }else if(res.data.errCode==0){
          my.redirectTo({ url: '../pay-success/pay-success' });
        }
      }
    });
  }
});
